package com.heima.kafka.sample;

import org.apache.kafka.clients.producer.*;

import java.util.Properties;

/**
 * 生产者
 */
public class ProducerQuickStart {

    public static void main(String[] args) {
        // 1. Kafka的配置信息
        Properties properties = new Properties();
        // Kafka的连接地址
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.200.130:9092");
        // 发送失败，失败的重试次数
        properties.put(ProducerConfig.RETRIES_CONFIG, 5);
        // 消息key的序列化器
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        // 消息value的序列化器
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        // ack配置 消息确认机制
        properties.put(ProducerConfig.ACKS_CONFIG, "all");
        // 数据压缩
        properties.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, "gzip");
        // 设置消息最大大小（可选）
        properties.put(ProducerConfig.MAX_REQUEST_SIZE_CONFIG, 1048576); // 1MB

        // 2. 生产者对象
        KafkaProducer<String, String> producer = new KafkaProducer<>(properties);

        // 封装发送的消息
        ProducerRecord<String, String> record = new ProducerRecord<>("itheima-topic", "hello kafka");

        // 3. 异步消息发送
        producer.send(record, new Callback() {
            @Override
            public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                if (e != null) {
                    System.err.println("发送失败，异常信息：" + e.getMessage());
                } else {
                    System.out.println("消息发送成功，偏移量：" + recordMetadata.offset());
                }
            }
        });

        // 4. 关闭消息通道，确保消息发送成功
        producer.close();
    }
}
